import React, { useState, useEffect } from 'react';
import axios from 'axios';

const SocialPositionsForm = ({ applicationId }) => {
    const [socialPositions, setSocialPositions] = useState([]);
    const [newPosition, setNewPosition] = useState({
        startDate: '',
        endDate: '',
        position: '',
        organizationName: '',
        remarks: ''
    });
    const [editingId, setEditingId] = useState(null);

    useEffect(() => {
        const fetchSocialPositions = async () => {
            try {
                const response = await axios.get(`/api/applications/${applicationId}/social-positions`);
                setSocialPositions(response.data);
            } catch (error) {
                console.error('Error fetching social positions:', error);
            }
        };

        if (applicationId) {
            fetchSocialPositions();
        }
    }, [applicationId]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setNewPosition(prevInfo => ({
            ...prevInfo,
            [name]: value
        }));
    };

    const handleAddOrUpdate = async (e) => {
        e.preventDefault();
        try {
            if (editingId) {
                await axios.put(`/api/applications/${applicationId}/social-positions/${editingId}`, newPosition);
                alert('社会兼职情况更新成功！');
            } else {
                await axios.post(`/api/applications/${applicationId}/social-positions`, newPosition);
                alert('社会兼职情况添加成功！');
            }
            setNewPosition({
                startDate: '',
                endDate: '',
                position: '',
                organizationName: '',
                remarks: ''
            });
            setEditingId(null);
            const response = await axios.get(`/api/applications/${applicationId}/social-positions`);
            setSocialPositions(response.data);
        } catch (error) {
            console.error('Error saving social position:', error);
            alert('保存失败，请重试。');
        }
    };

    const handleEdit = (info) => {
        setNewPosition(info);
        setEditingId(info.id);
    };

    const handleDelete = async (id) => {
        try {
            await axios.delete(`/api/applications/${applicationId}/social-positions/${id}`);
            alert('社会兼职情况删除成功！');
            setSocialPositions(socialPositions.filter(info => info.id !== id));
        } catch (error) {
            console.error('Error deleting social position:', error);
            alert('删除失败，请重试。');
        }
    };

    return (
        <div className="form-container">
            <h3>社会兼职情况</h3>
            <form onSubmit={handleAddOrUpdate}>
                <div className="form-group">
                    <label>开始日期:</label>
                    <input type="date" name="startDate" value={newPosition.startDate} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label>结束日期:</label>
                    <input type="date" name="endDate" value={newPosition.endDate} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>职务:</label>
                    <input type="text" name="position" value={newPosition.position} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>单位名称:</label>
                    <input type="text" name="organizationName" value={newPosition.organizationName} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>备注:</label>
                    <textarea name="remarks" value={newPosition.remarks} onChange={handleChange}></textarea>
                </div>
                <button type="submit">{editingId ? '更新' : '添加'}</button>
            </form>

            <h4>已添加社会兼职情况</h4>
            <table>
                <thead>
                    <tr>
                        <th>开始日期</th>
                        <th>结束日期</th>
                        <th>职务</th>
                        <th>单位名称</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {socialPositions.map(info => (
                        <tr key={info.id}>
                            <td>{info.startDate}</td>
                            <td>{info.endDate}</td>
                            <td>{info.position}</td>
                            <td>{info.organizationName}</td>
                            <td>{info.remarks}</td>
                            <td>
                                <button onClick={() => handleEdit(info)}>编辑</button>
                                <button onClick={() => handleDelete(info.id)}>删除</button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default SocialPositionsForm;

